﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Entity.DbEntity.sys;
using Entity.FrameEntity;
using System.Net.Http.Headers;
using Entity;
using Tools;

namespace SysFramework
{
    public class PubMethod
    {
     

        /// <summary>
        /// 获取当前时间(yyyy-MM-dd HH:mm:ss)
        /// </summary>
        /// <returns></returns>
        public string getNow(int days = 0)
        {
            if (days == 0)
            {
                return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            }
            else
            {
                return DateTime.Now.AddDays(days).ToString("yyyy-MM-dd HH:mm:ss");
            }
        }
        /// <summary>
        /// 获取当前时间(yyyy-MM-dd)
        /// </summary>
        /// <returns></returns>
        public string getNowDate(int days = 0)
        {
            if (days == 0)
            {
                return DateTime.Now.ToString("yyyy-MM-dd");
            }
            else
            {
                return DateTime.Now.AddDays(days).ToString("yyyy-MM-dd");
            }
        }
        /// <summary>
        /// 获取时间字符串(yyyyMMddHHmmss)
        /// </summary>
        /// <returns></returns>
        public string getTimeString(int days = 0)
        {
            if (days == 0)
            {
                return DateTime.Now.ToString("yyyyMMddHHmmssfff");
            }
            else
            {
                return DateTime.Now.AddDays(days).ToString("yyyyMMddHHmmssfff");
            }

        }
        /// <summary>
        /// 创建检索条件
        /// </summary>
        /// <param name="sb"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public StringBuilder CreateSelectCondition(StringBuilder sb, string condition,string exitFields="")
        {
            if (!string.IsNullOrWhiteSpace(condition))
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                var arr = exitFields.Split(';');
                foreach (JProperty obj in json.Properties())
                {
                    bool isQuery = true;
                    string exitValues = "";
                    foreach (string qf in arr)
                    {
                        if (string.IsNullOrWhiteSpace(qf))
                        {
                            break;
                        }
                        else
                        {
                            var sp = qf.Split('-');
                            if (obj.Name == sp[0].ToString())
                            {
                                if (sp.Length > 1 && !string.IsNullOrWhiteSpace(sp[1]))
                                {
                                    exitValues = sp[1];
                                }
                                else
                                {
                                    isQuery = false; 
                                }
                                break;
                            }
                        }
                    }
                    #region
                    //if (!string.IsNullOrWhiteSpace(exitFields))
                    //{
                    //    foreach (string str in arr)
                    //    {
                    //        var sArr = str.Split('-');
                    //        if (sArr.Length < 2)
                    //        {
                    //            isQuery = false; break;
                    //        }
                    //        if (string.IsNullOrWhiteSpace(sArr[0]))
                    //        {
                    //            continue;
                    //        }
                    //        if (sArr[0].Trim() == obj.Name.Trim() && !string.IsNullOrWhiteSpace(sArr[1]))
                    //        {
                    //            var vArr = sArr[1].Split(',');
                    //            foreach (string v in vArr)
                    //            {
                    //                if (!string.IsNullOrWhiteSpace(v))
                    //                {
                    //                    if (obj.Value.ToString() == v)
                    //                    {
                    //                        isQuery = false; break;
                    //                    }
                    //                }
                    //            }
                    //        }
                    //    }
                    //}
                    #endregion
                    if (isQuery)
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            var vArr = exitValues.Split(',');
                            foreach (string s in vArr)
                            {
                                if (!string.IsNullOrWhiteSpace(s))
                                {
                                    if (obj.Value.ToString() == s.Trim())
                                    {
                                        isQuery = false;break;
                                    }
                                }
                            }
                            if (isQuery)
                            {
                                if (!string.IsNullOrWhiteSpace(sb.ToString()))
                                {
                                    sb.Append(" and ");
                                }
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }
                           
                        }
                    }
                  
                }
            }
            return sb;
        }
        /// <summary>
        /// 创建编码
        /// </summary>
        /// <param name="codeType">数据类型</param>
        /// <param name="memo">备注</param>
        /// <param name="barLength">流水码长度</param>
        /// <param name="codeCount">条码个数</param>
        /// <returns></returns>
        public string CreateCodeInfo(string codeType, string memo, string barLength, int codeCount = 1)
        {
            CommandService.Commands cmd = new CommandService.Commands();
            try
            {
                StringBuilder sb = new StringBuilder();
                if (string.IsNullOrWhiteSpace(barLength) || int.Parse(barLength) < 1)
                {
                    barLength = "4";
                    sb.Append("select isnull(parValue,'') parValue from sys_parameters_info where ");
                    sb.Append("parCode='BarCodeLeng' and isDel=0 and enable='open'");
                    var parTable = cmd.GetDataTable(sb.ToString());
                    if (parTable.Rows.Count > 0 && !string.IsNullOrWhiteSpace(parTable.Rows[0][0].ToString()))
                    {
                        barLength = parTable.Rows[0][0].ToString(); //流水号长度
                    }
                }
                string date = DateTime.Now.ToString("yy-MM-dd");
                string sql = "select * from sys_SystemCodes_Bank where date='" + date + "' and tCode='" + codeType + "'";
                var table = cmd.GetDataTable(sql);
                DbCodeBank code = new DbCodeBank();
                code.date = date;
                code.tCode = codeType;
                int startNum = 0;
                OperateModel op = new OperateModel();
                if (table.Rows.Count < 1)
                {
                    #region 不存在记录
                    //startNum = 1;
                    startNum = 0;
                    code.memo = memo;
                    code.num = codeCount;
                    op.Types = OperateModel.OperateType.Add;

                    #endregion
                }
                else
                {
                    #region 存在记录
                    startNum = int.Parse(table.Rows[0]["num"].ToString());
                    code = new DbCodeBank();
                    code.Id = int.Parse(table.Rows[0]["id"].ToString());
                    code.num = int.Parse(table.Rows[0]["num"].ToString()) + codeCount;
                    op.Types = OperateModel.OperateType.Edit;
                    op.Conditions = "Id";
                    #endregion
                }
                op.Data = code;
                List<OperateModel> list = new List<OperateModel>();
                list.Add(op);
                var r = cmd.MoreUpdate(list);
                if (r.Result)
                {
                    string codes = "";
                    #region 生成唯一标识码
                    for (int i = 1; i <= codeCount; i++)
                    {
                        startNum++;
                        string newNum = "";
                        newNum = startNum.ToString().PadLeft(int.Parse(barLength), '0');
                        codes += string.Format("{0}{1}{2},", codeType.ToUpper(), date.Replace("-", ""), newNum);
                    }
                    #endregion
                    return codes.TrimEnd(',');

                }
            }
            catch (Exception ex)
            {
               
            }
            return null;
        }
        /// <summary>
        /// 根据关键码批次+关键码生成条码(旭日包装)
        /// </summary>
        /// <param name="codeType"></param>
        /// <param name="memo"></param>
        /// <param name="barLength"></param>
        /// <param name="batchCode"></param>
        /// <param name="codeCount"></param>
        /// <returns></returns>
        public string CreateBarCodeXR(string codeType, string memo, string barLength,string batchCode, int codeCount = 1)
        {
            CommandService.Commands cmd = new CommandService.Commands();
            try
            {
                StringBuilder sb = new StringBuilder();
                if (string.IsNullOrWhiteSpace(barLength) || int.Parse(barLength) < 1)
                {
                    barLength = "4";
                    sb.Append("select isnull(parValue,'') parValue from sys_parameters_info where ");
                    sb.Append("parCode='BarCodeLeng' and isDel=0 and enable='open'");
                    var parTable = cmd.GetDataTable(sb.ToString());
                    if (parTable.Rows.Count > 0 && !string.IsNullOrWhiteSpace(parTable.Rows[0][0].ToString()))
                    {
                        barLength = parTable.Rows[0][0].ToString(); //流水号长度
                    }
                }
                string date = DateTime.Now.ToString("yy-MM-dd");
                if (string.IsNullOrWhiteSpace(batchCode))
                {
                    date = batchCode;
                }
            
                string sql = "select * from sys_SystemCodes_Bank where date='" + date + "' and tCode='" + codeType + "'";
                var table = cmd.GetDataTable(sql);
                DbCodeBank code = new DbCodeBank();
                code.date = date;
                code.tCode = codeType;
                int startNum = 0;
                OperateModel op = new OperateModel();
                if (table.Rows.Count < 1)
                {
                    #region 不存在记录
                    //startNum = 1;
                    startNum = 0;
                    code.memo = memo;
                    code.num = codeCount;
                    op.Types = OperateModel.OperateType.Add;

                    #endregion
                }
                else
                {
                    #region 存在记录
                    startNum = int.Parse(table.Rows[0]["num"].ToString());
                    code = new DbCodeBank();
                    code.Id = int.Parse(table.Rows[0]["id"].ToString());
                    code.num = int.Parse(table.Rows[0]["num"].ToString()) + codeCount;
                    op.Types = OperateModel.OperateType.Edit;
                    op.Conditions = "Id";
                    #endregion
                }
                op.Data = code;
                List<OperateModel> list = new List<OperateModel>();
                list.Add(op);
                var r = cmd.MoreUpdate(list);
                if (r.Result)
                {
                    string codes = "";
                    #region 生成唯一标识码
                    for (int i = 1; i <= codeCount; i++)
                    {
                        startNum++;
                        string newNum = "";
                        newNum = startNum.ToString().PadLeft(int.Parse(barLength), '0');
                        codes += string.Format("{0}{1}{2},", codeType.ToUpper(), date.Replace("-", ""), newNum);
                    }
                    #endregion
                    return codes.TrimEnd(',');

                }
            }
            catch (Exception ex)
            {

            }
            return null;
        }
        /// <summary>
        /// 创建列表项样式数据
        /// </summary>
        /// <param name="hList"></param>
        /// <param name="code"></param>
        /// <param name="name"></param>
        /// <param name="type"></param>
        public void createHead(ref List<Dictionary<string, string>> hList, string code, string name, string color = null, string fontSize = null, bool isOver = false, string type = null)
        {
            var dic = new Dictionary<string, string>();
            dic.Add("code", code);
            dic.Add("name", name);
            if (!string.IsNullOrWhiteSpace(type))
            {
                dic.Add("type", type);
            }
            if (!string.IsNullOrWhiteSpace(fontSize))
            {
                dic.Add("fontSize", fontSize);
            }
            if (!string.IsNullOrWhiteSpace(color))
            {
                dic.Add("color", color);
            }
            //因为boolean类型直接转为字符串首字母会大写，所以要在转为小写
            dic.Add("isOver", isOver.ToString().ToLower());
            hList.Add(dic);
        }
       
        public ReturnResult GetLicense(string cuCode)
        {
            ReturnResult rsl = new ReturnResult();
            try
            {
                var dic = new Dictionary<string, string>();
                dic.Add("cuCode", cuCode);
                HttpAgreement http = new HttpAgreement();
                var url=AppSettingHelper.ReadAppSettings("sqUrl") + "/Services/GetSysLicense";
                var info= http.PostJson(url, JsonConvert.SerializeObject(dic));
                if (!string.IsNullOrWhiteSpace(info))
                {
                    rsl = JsonConvert.DeserializeObject<ReturnResult>(info);
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

    }
}
